/**
 * 
 * Copyright (C) 2015 by Elcom Software Company
 *
 * @id: JobCmd.java, Mar 13, 2015
 *
 */
package com.nip.commons.job;

import com.nip.commons.job.interf.IJob;
import com.nip.commons.job.interf.IJobSchedule;
import com.nip.commons.job.interf.IJobTime;

/**
 * @author ThangNM<thangnm@elcom.com.vn>
 * 
 * @version v
 */
public abstract class JobCmd implements IJob {

    private boolean isDone = true;
    private IJobSchedule jobSchedule;

    private final Runnable run = new Runnable() {

        @Override
        public void run() {
            execute();
            isDone = true;
        }
    };

    public JobCmd() {
    }

    @Override
    public void notify(IJobTime time) {
        
        if(jobSchedule.getStartDate() !=null && jobSchedule.getStartDate().getTime() > time.getTime().getTime())
        {
            return;
        }
        
        if(!this.jobSchedule.getMinute().checkSchedule(time.getMunite()))
            return;
        if(!this.jobSchedule.getHour().checkSchedule(time.getHour()))
            return;
        if(!this.jobSchedule.getDay().checkSchedule(time.getDay()))
            return;
        if(!this.jobSchedule.getMonth().checkSchedule(time.getMonth()))
            return;
        if(!this.jobSchedule.getYear().checkSchedule(time.getYear()))
            return;
        if(!this.jobSchedule.getDayOfWeek().checkSchedule(time.getDayOfWeek()))
            return;
        
        if(isDone)
        {
            new Thread(run).start();
            isDone = false;
        }
    }

    /* (non-Javadoc)
     * @see com.nip.commons.job.interf.IJob#notify(com.nip.commons.job.interf.IJobTime, boolean)
     */
    @Override
    public void notify(IJobTime time, boolean isExecute) {
        
        if(!this.jobSchedule.getMinute().checkSchedule(time.getMunite()))
            return;
        if(!this.jobSchedule.getHour().checkSchedule(time.getHour()))
            return;
        if(!this.jobSchedule.getDay().checkSchedule(time.getDay()))
            return;
        if(!this.jobSchedule.getMonth().checkSchedule(time.getMonth()))
            return;
        if(!this.jobSchedule.getYear().checkSchedule(time.getYear()))
            return;
        if(!this.jobSchedule.getDayOfWeek().checkSchedule(time.getDayOfWeek()))
            return;
        
        new Thread(new Runnable() {
            
            @Override
            public void run() {
                execute();
            }
        }).start();
    }
    
    /*
     * (non-Javadoc)
     * 
     * @see
     * com.nip.commons.job.interf.IJob#setSchedule(com.nip.commons.job.interf
     * .IJobSchedule)
     */
    @Override
    public void setSchedule(IJobSchedule schedule) {
        this.jobSchedule = schedule;

    }
}
